<template>
  <section :class="isDetail ? 'detailContent' : 'content'">
    <details-head v-if="isDetail"
                  :title="`详情`"
                  :multiple="true" />
    <el-form ref="ruleForm"
             class="form"
             label-width="100px"
             :model="form"
             label-position="right"
             size="small">
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item :label="billType === 1?'收款时间':'付款时间'"
                        prop="bizAt">
            <div>{{form.bizAt}}</div>
          </el-form-item>
          <el-form-item :label="billType === 1?'发货方名称':'承运方名称'"
                        :prop="`${billType === 1 ? 'customerName' : 'carrierName'}`">
            <div>
              <Tooltip v-if="iconName"
                       :content="content"
                       :placement="placement">
                <icon-svg class-name="iconClass mr5"
                          :icon-name="iconName" />
              </Tooltip>
              {{billType === 1 ? (form.showCustomerName  || form.customerName) : form.carrierName}}
            </div>
          </el-form-item>
          <el-form-item label="支付方式"
                        prop="payMode"
                        :rules="[{ required: true, message: `请选择支付方式`, trigger: 'change' }]">
            <div v-if="isDetail">{{form.payModeDesc}}</div>
            <Select v-else
                    v-model="form.payMode"
                    :options="payModeOptions"
                    :placeholder="'请选择支付方式'" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="billType === 1?'收款单号':'付款单号'"
                        prop="no">
            <div>{{form.no}}</div>
          </el-form-item>
          <el-form-item :label="billType === 1?'收款类型':'付款类型'"
                        prop="billRecordTypeDesc">
            <div>{{form.billRecordTypeDesc}}</div>
          </el-form-item>
          <!-- :rules="[{ required: form.payMode === 2, message: `请输入银行卡号`, trigger: 'blur' }]" -->
          <el-form-item label="银行卡号"
                        prop="bankAccount">
            <div v-if="isDetail">{{form.bankAccount}}</div>
            <el-input v-else
                      v-model="form.bankAccount"
                      placeholder="请输入银行卡号"
                      oninput="this.value=(this.value.match(/^[0-9]*$/));"
                      maxlength="20" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item v-if="billRecordType!=4 && !isOneBill"
                        :label="combineContractNo ? '合单编号' : '合同编号'"
                        prop="contractNo">
            <div>{{combineContractNo || contractNo}}</div>
          </el-form-item>
          <el-form-item label="金额"
                        prop="money">
            <div>{{form.money}}</div>
          </el-form-item>
        </el-col>
        <el-col v-if="!isDetail"
                :span="6"
                class="footer-item">
          <el-button type="primary"
                     plain
                     @click="back">返回</el-button>
          <el-button type="primary"
                     @click="submit">{{billType === 1?'收':'付'}}款</el-button>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="16">
          <el-form-item label="摘要:"
                        prop="desc">
            <div v-if="isDetail"
                 class="descSty">{{form.desc || '--'}}</div>
            <el-input v-else
                      v-model="form.desc"
                      type="textarea"
                      :rows="5"
                      maxlength="200"
                      show-word-limit
                      placeholder="请输入摘要"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <way-bill-list :col-width="160"
                   :bill-record-id="billRecordId"
                   :page="page"
                   :page-size="pageSize"
                   :current-data="currentData"
                   :total-data="totalData"
                   :bill-type="billType"
                   :bill-record-type="billRecordType"
                   :table-loading.sync="tableLoading"
                   ship-or-send />
    <div v-if="billRecordType===4 && total>1"
         class="footer-item mt12">
      <el-pagination :current-page="page"
                     :page-size="pageSize"
                     :total="total"
                     :page-sizes="[10, 50, 100, 500, 1000]"
                     layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange">
      </el-pagination>
    </div>
  </section>
</template>

<script>
import DetailsHead from "@/components/detailsHead/Header";
import WayBillList from './components/WayBillList.vue'
import { returnThousandDigit } from "@/libs/util.js";
import { pageTotal, billCache } from "../createAccountStatement/components/financeMap";
import Tooltip from "@components/basic/Tooltip.vue";
import { finance } from '@/api/index'
import Select from "@/components/advance/Select";
import { payModeOptions } from "@/libs/constant.js"
import _ from 'lodash'
export default {
  name: 'BillPayment',
  components: {
    Select,
    WayBillList,
    DetailsHead,
    Tooltip
  },
  props: {
    query: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      api: finance,
      page: 1,
      pageSize: 10,
      total: 0,
      currentData: [],  //当前页数据
      combineContractNo: '',
      contractNo: '',
      totalData: [{ contractNo: '本页小计' }, { contractNo: '全部合计' }], //合计数据源
      form: {
        bankAccount: null,
        payMode: null,
        desc: null,
        bizAt: '自动生成'
      },
      pageTotal,       //本页小计
      billCache,       //全部合计
      tableLoading: false,
      payModeOptions
    }
  },
  computed: {
    billRecordId () {
      return Number(this.$route.query?.billRecordId)
    },
    billRecordType () {
      // 付款类型 1 预付 2 到付 3 代收 4 回执
      return this.form?.billRecordType
    },
    billType () {
      // 类型 1应收 2应付
      const { name } = this.$route
      return ['custometBillPayment', 'custometBillPaymentWindow'].includes(name) ? 1 : 2
    },
    isDetail () {
      // 是否显示为详情页
      const { name } = this.$route
      return ['billPaymentWindow', 'custometBillPaymentWindow'].includes(name)
    },
    isOneBill () {
      // 是否为合单
      return this.$route.query?.isOneBill
    },
    params () {
      return {
        billRecordId: this.billRecordId,
        page: this.page,
        size: this.pageSize,
        sort: [{ asc: false, name: 'fromTime' }]
      }
    },
    placement () {
      return 'top'
    },
    content () {
      const { carrierType, customerType, carrierExtraType } = this.form
      if (this.billType === 1) {
        switch (customerType) {
          case 0:
            return '线下';
          case 1:
            return '线上';
          default:
            return '';
        }
      } else {
        if (carrierType === 0) {
          return '线下'
        }
        if (carrierType === 1 && carrierExtraType == 0) {
          return '线上'
        }
      }
      return '';
    },
    iconName () {
      const { carrierType, customerType, carrierExtraType } = this.form
      if (this.billType === 1) {
        switch (customerType) {
          case 0:
            return 'xianxia';
          case 1:
            return 'xianshang';
          default:
            return '';
        }
      } else {
        if (carrierType === 0) {
          return 'xianxia'
        }
        if (carrierType === 1 && carrierExtraType == 0) {
          return 'xianshang'
        }
      }
      return '';
    }
  },
  created () {
    this.pageSize = this.isDetail ? 100 : 10;
    this.getBillInfo();
  },
  methods: {
    // 分页数量改变
    handleSizeChange (value) {
      this.page = 1
      this.pageSize = value
      this.getBillInfo();
    },
    // 当前页数改变
    handleCurrentChange (value) {
      this.page = value
      this.getBillInfo()
    },
    // 对账单详情
    async getBillInfo () {
      this.tableLoading = true;
      let { data } = await finance.getBillInfo(this.params).catch(err => {
        this.tableLoading = false;
      })
      this.tableLoading = false;
      this.combineContractNo = data?.combineContractNo
      this.contractNo = data?.contractNo
      this.form = { ...this.form, ...data }
      this.form.money = this.form.money ? returnThousandDigit(this.form.money, 2) : 0;
      this.currentData = data.waybills?.page?.records
      this.total = data.waybills?.page?.total
      // this.currentData = this.addTableFooter(data.billSpecs.records, data.pageTotal, data.billCache)
      this.totalData = this.addTableFooter(data.pageTotal, data.billCache)
    },
    // 合计表数据源
    addTableFooter (page, total) {     // 合计表数据源
      return [{
        contractNo: '本页小计',
        ...pageTotal,
        ...page
      }, {
        contractNo: "全部合计",
        ...billCache,
        ...total
      }];
    },
    // 收付款
    async paymentOrCollect (url) {
      await finance[url]({ billRecordId: this.billRecordId, bankAccount: this.form.bankAccount, desc: this.form.desc, payMode: this.form.payMode })
      this.$message.success("操作成功！")
      this.back();
    },
    // 触发事件
    submit: _.debounce(function () {    // 触发事件
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.$confirm(`是否确认${this.billType === 1 ? '收' : '付'}款`, '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.paymentOrCollect(this.billType === 1 ? 'billCollect' : 'billPayment')
          })
        }
      })
    }, 600),
    back () {
      this.$router.back()
    },
  }
}
</script>
<style lang="scss" scoped>
.detailContent {
  width: 1200px;
  height: calc(100vh);
  overflow-x: hidden;
  overflow-y: scroll;
  background: var(--prev-bg-white);
  margin: 0 auto;
}
.content {
  background: var(--prev-bg-white);
  padding: 20px;
  position: relative;
  height: 88vh;
  overflow-y: auto;
}
.form {
  padding: 20px;
}
.footer-item {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.mt12 {
  margin-top: 12px;
}
.descSty {
  word-break: break-all;
}
.iconClass {
  width: 14px;
  height: 14px;
}
</style>
